<script setup lang="ts">
import { reactive, onMounted, watch } from 'vue';
import { eventCenter, getCurrentInstance, showToast } from '@tarojs/taro';
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';
import { Search2 as AppNutIconSearch2 } from '@nutui/icons-vue-taro';
const props = defineProps<{
  /**
   * 显示已经选过的值
   */
  selectedValue?: string;
  names: string[];
  placeholder: string;
}>();

const emits = defineEmits<{
  (e: 'onChange', value: string): void;
}>();
//局部
const state: {
  radioVal: string;
  radioPickerVisible: boolean;
  keyword: string;
  list: string[];
} = reactive({
  radioVal: '',
  radioPickerVisible: false,
  keyword: '',
  list: [],
});
//初始化
state.list.push(...props.names);
if (props.placeholder === '请选择物品规格') {
  watch(props.names, () => {
    state.list.push(...props.names);
  });
}
watch(
  () => state.keyword,
  () => {
    if (state.keyword.length > 0) {
      state.list = [...props.names.filter((name) => name.includes(state.keyword))];
    } else {
      state.list = [...props.names];
    }
  },
);
if (props.selectedValue) {
  state.radioVal = props.selectedValue;
}

function clickHandle() {
  if (props.placeholder === '请选择物品规格' && props.names.length === 0) {
    showToast({ title: '请先选择物品类型', icon: 'error' });
    return;
  }
  state.radioPickerVisible = !state.radioPickerVisible;
}

function confirm({ selectedOptions }: any) {
  const value = selectedOptions[0].value;
  emits('onChange', value);
  state.radioPickerVisible = false;
  state.radioVal = value;
}
onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态
    state.radioVal = '';
    state.radioPickerVisible = false;
  });
});

defineExpose({ state });
</script>
<template>
  <view v-bind="$attrs" class="item-type-product-picker" @click="clickHandle">
    <text>{{ state.radioVal || props.placeholder }}</text>
    <app-nut-icon-right />
  </view>
  <nut-popup position="bottom" v-model:visible="state.radioPickerVisible">
    <nut-picker
      :columns="
        state.list.map((item) => {
          return {
            text: item,
            value: item,
          };
        })
      "
      :title="placeholder"
      @close="state.radioPickerVisible = false"
      @confirm="confirm"
      @cancel="state.radioPickerVisible = false"
    >
      <template #top>
        <nut-searchbar v-model="state.keyword" placeholder="请搜索物品类型名称">
          <template #leftin>
            <app-nut-icon-search2 />
          </template>
        </nut-searchbar>
      </template>
    </nut-picker>
  </nut-popup>
</template>
<style lang="scss">
.item-type-product-picker {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
